package cn.sytton.taffe.framework.base.service;

import cn.sytton.taffe.framework.base.entity.BaseEntity;
import cn.sytton.taffe.framework.base.entity.BaseUpdatedEntity;
import cn.sytton.taffe.framework.base.entity.PageParam;
import cn.sytton.taffe.framework.base.mapper.BaseMapper;
import cn.sytton.taffe.framework.mybatis.SortHelper;
import cn.sytton.taffe.framework.util.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;

/**
 * 服务层基类
 *
 * @author skyrock
 */
@Slf4j
public class BaseService<M extends BaseMapper<T>, T extends BaseEntity>
        extends ServiceImpl<M, T>
        implements IBaseService<T> {

    public PageInfo<T> findPage(PageParam pp) {
        setPageParams(pp);
        return new PageInfo<>(listByMap(pp.getParams()));
    }

    public PageInfo<T> findListPageOfXml(PageParam pp) {
        setPageParams(pp);
        return new PageInfo<>(baseMapper.findListOfXml(pp.getParams()));
    }

    protected void setPageParams(PageParam pp) {
        PageHelper.startPage(pp.getPageNum(),
                pp.getPageSize(),
                SortHelper.convertGbk(pp.getSort()),
                pp.getFilter());
    }

    @Override
    public T findById(String id) {
        return getById(id);
    }

    @Override
    public void create(T entity) {
        save(entity);
    }

    @Override
    public void update(T entity) {
        updateById(entity);
    }

    @Override
    public void createOrUpdate(T entity) {
        saveOrUpdate(entity);
    }

    @Override
    public void updateWithUpdateField(Wrapper<T> updateWrapper) {
        if (updateWrapper instanceof LambdaUpdateWrapper) {
            ((LambdaUpdateWrapper<BaseUpdatedEntity>)updateWrapper)
                    .set(BaseUpdatedEntity::getUpdatedUserId, SecurityUtil.getUserId())
                    .set(BaseUpdatedEntity::getUpdatedTime, new Timestamp(new Date().getTime()));
        } else if (updateWrapper instanceof UpdateWrapper) {
            ((UpdateWrapper<BaseUpdatedEntity>)updateWrapper)
                    .set("updatedUserId", SecurityUtil.getUserId())
                    .set("updatedTime", new Timestamp(new Date().getTime()));
        }
        update(updateWrapper);
    }

    @Override
    public void delete(String... ids) {
        if (ids == null || ids.length == 0) {
            log.debug("删除的主键ID数组为空");
        } else {
            removeByIds(Arrays.asList(ids));
        }
    }
}
